package com.hzdp.netty.split;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

import org.apache.log4j.Logger;

public class TimeServerHandler extends ChannelHandlerAdapter {

	protected static Logger logger = Logger.getLogger(TimeServerHandler.class);

	private int count;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);

		String property = System.getProperty("line.separator");
		String body = new String(req, "UTF-8").substring(0, req.length - property.length());
		logger.info("Server: received:" + body + ";counter=" + ++count);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";
		currentTime = currentTime + property;
		ctx.writeAndFlush(Unpooled.copiedBuffer(currentTime.getBytes()));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
